package cn.darxs.noquestion.controller;

import cn.darxs.noquestion.common.Response;
import cn.darxs.noquestion.entity.Question;
import cn.darxs.noquestion.service.QuestionService;
import net.minidev.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;

import java.io.*;
import java.nio.charset.StandardCharsets;

import static cn.darxs.noquestion.common.ResponseStateCode.*;

@RestController
@RequestMapping("/question")
public class QuestionController {

    @Autowired
    QuestionService questionService;

    /**
     * 创建问题
     *
     * @param
     * @return
     */
    @PostMapping
    public Response questionCreate(HttpServletRequest request, @RequestBody JSONObject params) {
        Response response = new Response();
        try {
            String userId = (String) request.getSession().getAttribute("userId");
            if (userId == null) {
                response.setCode(NO_LOGIN);
            } else {
                Question question = new Question();
                question.setDescription((String) params.get("description"));
                question.setType((Integer) params.get("type"));
                question.setCreateUserId(Long.valueOf(userId));
                questionService.save(question);
                response.setCode(OPERATION_SUCCEED);
            }
        } catch (Exception e) {
            response.setCode(RENTER_CREATE_FAILURE);
        }
        return response;
    }

    @PostMapping("/file")
    public Response questionCreateByFile(HttpServletRequest request, @RequestBody MultipartFile file) {
        Response response = new Response();
        try {
            handleFile(file, "1");
            String userId = (String) request.getSession().getAttribute("userId");
            if (userId == null) {
                response.setCode(NO_LOGIN);
            } else {
                response.setCode(OPERATION_SUCCEED);
            }
        } catch (Exception e) {
            response.setCode(RENTER_CREATE_FAILURE);
        }
        return response;
    }

    private void handleFile(MultipartFile multipartFile, String userId) throws IOException {

        InputStream inputStream = multipartFile.getInputStream();
        String str[] = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
                .lines()
                .toArray(String[]::new);
        for (String s :
                str) {
            handleLine(s, userId);
        }
    }

    private void handleLine(String s, String userId) {
        String Str[] = s.split(",");
        Question question = new Question();
        question.setCreateUserId(Long.valueOf(userId));
        question.setDescription(Str[0]);
        question.setType(Integer.parseInt(Str[1]));
        questionService.save(question);
    }

}
